import { useEffect, useRef, useState } from 'react';

export interface CounterProps {
    timer: number;
    onTimeout?: () => void;
    formatTime?: boolean;
    syncTime?: Function;
}

function format(time: number) {
    // Hours, minutes and seconds
    const hrs = ~~(time / 3600);
    const mins = ~~((time % 3600) / 60);
    const secs = ~~time % 60;

    // Output like "1:01" or "4:03:59" or "123:03:59"
    let ret = '';
    if (hrs > 0) {
        ret += '' + hrs + ':' + (mins < 10 ? '0' : '');
    }
    ret += '' + String(mins).padStart(2, '0') + ':' + (secs < 10 ? '0' : '');
    ret += '' + secs;
    return ret;
}

export default function Countdown(props: CounterProps) {
    const { timer, onTimeout, formatTime = true, syncTime } = props;
    const [counter, setCounter] = useState(timer);
    const counterRef = useRef(counter);

    useEffect(() => {
        const timer =
            counter > 0 &&
            setInterval(() => {
                const newCounter = counter - 1;
                counterRef.current = newCounter;
                if (newCounter === 0) {
                    onTimeout();
                }
                setCounter(newCounter);
            }, 1000);
        return () => clearInterval(timer);
    }, [counter]);

    useEffect(() => () => syncTime && syncTime(counterRef.current), []);

    return <>{formatTime ? format(counter) : counter}</>;
}
